﻿///<reference path="../../../Scripts/jquery-1.4.1-vsdoc.js"/>
///<reference path="../utils/Utils.js"/>

function CacheItem(key, priority, loadDataFunction, onLoadDataCompleted) {

    this.Key = key;
    this.Priority = priority;
    this.IsLoaded = false;
    this.Data;
    this.LoadDataFunction = loadDataFunction;
    this.LoadData = function () {  // only sync!!!
        if (!this.IsLoaded) {
            this.Data = this.LoadDataFunction.call(this);
            this.IsLoaded = true;
            if (onLoadDataCompleted != undefined)
                onLoadDataCompleted.call(this);
            return this.Data;
        }
    }  
}

function CacheManager() {
    this.cacheItems = new Dictionary();

    this.GetCacheItem = function (key) {        
        var cacheItem = this.cacheItems.Lookup(key);

        if (cacheItem == undefined)
        {
            appPointer.Logger.LogException(key + " key is not registered in cache.");
            return undefined;
        }

        if (cacheItem.IsLoaded)
            return cacheItem.Data;
        else        
            return cacheItem.LoadData();
    }

    // загружает все ещё не загруженные элементы, приоритет которых выше или равен указанному ( выше - значит меньше: 1 - самый высокий приоритет )
    this.InitializeCache = function (priority) {
        for (var i = 0; i < this.cacheItems.Keys.length; i++) {
            var cacheItem = this.cacheItems.Lookup(this.cacheItems.Keys[i]);
            if (cacheItem.Priority <= priority)
                cacheItem.LoadData();
        }
    }

    this.RegisterCacheItem = function (key, priority, loadDataFunction, onLoadDataCompleted) {
        this.cacheItems.Add(key, new CacheItem(key, priority, loadDataFunction, onLoadDataCompleted));
    }

    
}